package com.baiyinet.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.baiyinet.BuildConfig;
import com.baiyinet.MyApp;
import com.baiyinet.biz.CurrentUser;
import com.baiyinet.biz.PageStatus;
import com.baiyinet.biz.PushInfo;
import com.baiyinet.di.DaggerScope;
import com.baiyinet.di.Injector;
import com.baiyinet.ui.PushMsgDialogActivity;
import com.baiyinet.ui.PushMsgDialogActivity_;
import com.baiyinet.util.DialogUtils;

import org.json.JSONObject;
import org.parceler.Parcels;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import cn.jpush.android.api.JPushInterface;

/**
 * 极光自定义推送接收者
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(PushReceiver.class)
public class PushReceiver extends BroadcastReceiver {

    @Inject
    CurrentUser mCurrentUser;

    @Override
    public void onReceive(Context context, Intent intent) {
        // 不接收非自定义的推送消息
        if(!JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())
                && !JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            return;
        }

        if (mCurrentUser == null) {
            Injector.initPushReceiverComponent().inject(this);
        }

        PushInfo pushInfo = obtainPushExtra(intent);

        if(null == pushInfo) {
            return;
        }

        if(!pushInfo.detailUrl.startsWith("http")) {
            pushInfo.detailUrl = BuildConfig.ENDPOINT + pushInfo.detailUrl;
        }

        PageStatus pageStatus = new PageStatus(pushInfo.detailUrl, true, true, mCurrentUser.getToolbarBgColor());
        Intent newIntent = new Intent(context, PushMsgDialogActivity_.class);
        newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        newIntent.putExtra(PageStatus.EXTRA_NAME, Parcels.wrap(pageStatus));
        context.startActivity(newIntent);
    }

    /**
     * 获取推送实体
     * @param intent
     * @return
     */
    private PushInfo obtainPushExtra(Intent intent) {
        if(null == intent) {
            return null;
        }

        PushInfo pushInfo = new PushInfo();

        try {
            // 推送内容
            JSONObject extraObj = new JSONObject(intent.getStringExtra(JPushInterface.EXTRA_EXTRA));
            pushInfo.detailUrl = extraObj.optString("DetailUrl");
        }catch (Exception e) {
            Log.e("Error obtainPushExtra:", PushReceiver.class.getSimpleName());
            return null;
        }

        return pushInfo;
    }
}
